package main

import (
	"context"
	"flag"
	"fmt"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"path/filepath"
)

func main()  {
	kubeconfig := getconfig()
	clientset := getclientset(*kubeconfig)
	//createdep(clientset)  //创建deployment
	updatedep(clientset)    //更新镜像名称（更新服务）
	//createservice(clientset)  //创建service的方法
	//createns(clientset)     //创建ns的方法
	//deletesvc(clientset)  //删除svc的方法
	//deletedep(clientset)  //删除deployment的方法
	//deletens(clientset)  //删除namespace服务
}

func updatedep(clientset *kubernetes.Clientset) {
	//获取更新的资源
	deployment,err := clientset.AppsV1().Deployments("fuxing").Get(context.TODO(),"uiaap-ssg-web-login",metav1.GetOptions{})
	if err !=nil {
		panic(err.Error())
	}
	//更新
	deployment.Spec.Template.Spec.Containers[0].Image="harbor.assistfc.com/dev/uiaap-ssg-web-login:1.1.0-19e19d8c-202305121522"
	dep,err := clientset.AppsV1().Deployments("fuxing").Update(context.TODO(),deployment,metav1.UpdateOptions{})
	if err != nil{
		panic(err.Error())
	}
	fmt.Printf("deployment %s updated",dep.Name)
}

func createns(clientset *kubernetes.Clientset)  {
	ns := &corev1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			Name: "test",
		},
	}
	createnamespace,err := clientset.CoreV1().Namespaces().Create(context.TODO(),ns,metav1.CreateOptions{})
	if err != nil{
		panic(err.Error())
	}
	fmt.Printf("namespace %s created",createnamespace.Name)
}

func deletens(clientset *kubernetes.Clientset) {
	err := clientset.CoreV1().Namespaces().Delete(context.TODO(),"test",metav1.DeleteOptions{})
	if err != nil{
		panic(err.Error())
	}
}

func createdep(clientset *kubernetes.Clientset) {
	var Replicas int32 = 3
	deployment := &appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name: "uiaap-ssg-web-login",
			Namespace: "fuxing",
			Labels: map[string]string{
				"efssc-service": "uiaap-ssg-web-login",
			},
		},
		Spec: appsv1.DeploymentSpec{
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"efssc-service": "uiaap-ssg-web-login",
				},
			},
			Replicas: &Replicas,
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"efssc-service": "uiaap-ssg-web-login",
					},
				},
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{
						{
							Name: "uiaap-ssg-web-login",
							Image: "harbor.assistfc.com/dev/uiaap-ssg-web-login:1.1.0-837ddd64-202305151020",
							ImagePullPolicy: "Always",
							Ports: []corev1.ContainerPort{
								{Name: "rellport1",ContainerPort: 8080,Protocol: "TCP"},
							},
							Env: []corev1.EnvVar{
								{Name: "JAVA_OPS", Value: "-server -Xms256M -Xmx1024M -Xmn256m -Xss256k -XX:+UseConcMarkSweepGC\n            -XX:+UseParNewGC -XX:+CMSClassUnloadingEnabled -XX:+HeapDumpOnOutOfMemoryError\n            -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps\n            -Xloggc:/tmp/gc.log -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly\n            -javaagent:/opt/agent/skywalking-agent.jar -Dskywalking.agent.service_name=cesp-ssg-account\n            -Dskywalking.collector.backend_service=skywalking-oap.dev-sky.svc.cluster.local:11800"},
								{Name: "env_type", Value: "dev"},
							},
							ReadinessProbe: &corev1.Probe{
								FailureThreshold: 3,
								InitialDelaySeconds: 10,
								TimeoutSeconds: 3,
								PeriodSeconds: 10,
								SuccessThreshold: 1,
								ProbeHandler: corev1.ProbeHandler{
									HTTPGet: &corev1.HTTPGetAction{
										Port: intstr.FromInt(8080),
										Path: "/index.html",
										Scheme: corev1.URISchemeHTTP,
									},
								},
							},
						},
					},
				},
			},

		},
	}
	creatDeployment,err := clientset.AppsV1().Deployments("fuxing").Create(context.TODO(),deployment,metav1.CreateOptions{})
	if err != nil{
		panic(err.Error())
	}
	fmt.Printf("deployment %s created",creatDeployment.Name)
}

func createservice(clientset *kubernetes.Clientset) {
	service := &corev1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name: "uiaap-ssg-web-login",
			Namespace: "fuxing",
		},
		Spec: corev1.ServiceSpec{
			Ports: []corev1.ServicePort{
				{
					Name: "rellport1",
					Protocol: corev1.ProtocolTCP,
					TargetPort: intstr.FromInt(8080),
					Port: 8080,
				},
			},
			Selector: map[string]string{
				"efssc-service": "uiaap-ssg-web-login",
			},
			Type: corev1.ServiceTypeNodePort,
		},
	}
	createservice, err := clientset.CoreV1().Services("fuxing").Create(context.TODO(),service,metav1.CreateOptions{})
	if err != nil{
		panic(err.Error())
	}
	fmt.Printf("service %s created\n",createservice.Name)
}

func deletedep(clientset *kubernetes.Clientset)  {
	err := clientset.AppsV1().Deployments("fuxing").Delete(context.TODO(),"nginx1",metav1.DeleteOptions{})
	if err != nil{
		panic(err.Error())
	}
	fmt.Println("deployment deleted")
}

func deletesvc(clientset *kubernetes.Clientset)  {
	err := clientset.CoreV1().Services("fuxing").Delete(context.TODO(),"nginx1",metav1.DeleteOptions{})
	if err != nil{
		panic(err.Error())
	}
	fmt.Println("service deleted")
}

func getclientset(configfile string)(clientset *kubernetes.Clientset){
	config,err := clientcmd.BuildConfigFromFlags("", configfile)
	if err != nil{
		panic(err.Error())
	}
	clients, err := kubernetes.NewForConfig(config)
	if err != nil{
		panic(err.Error())
	}
	return clients
}

func getconfig() *string  {
	var kubeconfig *string
	if home := homedir.HomeDir();home != ""{
		kubeconfig = flag.String("kubeconfig",filepath.Join(home,".kube","config"),"option absolute path")
	}else {
		kubeconfig = flag.String("kubeconfig","","absolute config file path")
	}
	flag.Parse()
	return kubeconfig
}